package cn.congine.wizarpos.mall.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.common.Page;
import cn.congine.wizarpos.mall.entity.MrtMerchantCarousel;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.service.MrtMerchantCarouselService;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.WxSignUtil;

@Controller
@RequestMapping(value = "/index")
public class IndexAction {
	
	private static Logger logger = Logger.getLogger(IndexAction.class);;
	
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	
	@Autowired
	private MrtMerchantCarouselService mrtMerchantCarouselService;
	
	@Resource(name = "messageSource")
	private MessageSource messageSource;
	
	@RequestMapping(value = "/index")
	public ModelAndView index(@RequestParam(value = "mid") String mid,
			@RequestParam(value = "hotJudge", required = false) String hotJudge, 
			HttpServletRequest httpRequest) {
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput(); 
		producthotInput.setMid(mid);
		producthotInput.setHot(hotJudge);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();

		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput,"/merchantdef/info",MerchantDefQueryOutput.class);
		MerchantDef merchantDef = merchantDefQueryOutput.getResult();		
		
		if (StringUtils.isEmpty(merchantDef.getBannerImage()) && !StringUtils.isEmpty(merchantDef.getLogoImage())) {
			merchantDef.setBannerImage(Function.dealGridPicUrl(
					merchantDef.getLogoImage(), 700, 700));
		} else if (StringUtils.isEmpty(merchantDef.getBannerImage()) && StringUtils.isEmpty(merchantDef.getLogoImage())) {
			merchantDef.setBannerImage(SysConstants.DEFAULT_PICTURE_DETAIL);
		}		
	
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 300, 300));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		// 请求微信 js api的完整页面地址
		String baseUrl = getBaseURL(httpRequest);
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/index/index");
		tmpUrl.append("?mid=");
		tmpUrl.append(mid);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		data.put("dns", messageSource.getMessage(SysConstants.SERVICE_DNS, null,
				Locale.ENGLISH));
		
		data.put("merchant", merchantDef);
		data.put("getpricehot", getpricehot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("mid", mid);
		return new ModelAndView("index/index", data);
	}
	
	@RequestMapping(value = "/dgd_index")
	public ModelAndView dgdIndex(@RequestParam(value = "mid") String mid,
			HttpServletRequest httpRequest) {
		MerchandiseSyncInput productsInput = new MerchandiseSyncInput(); 
		productsInput.setMid(mid);
		productsInput.setPageNo("1"); // 分页，取前第一页的十个商品
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(productsInput,"/product/merchandise",MerchandiseSyncOutput.class);

		if (producthotOutput == null) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(producthotOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		}
		
//		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
//		merchantDefQueryInput.setMid(mid);
//		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput,"/merchantdef/info",MerchantDefQueryOutput.class);
//		MerchantDef merchantDef = merchantDefQueryOutput.getResult();		
//		
//		if (StringUtils.isEmpty(merchantDef.getBannerImage()) && !StringUtils.isEmpty(merchantDef.getLogoImage())) {
//			merchantDef.setBannerImage(Function.dealGridPicUrl(
//					merchantDef.getLogoImage(), 700, 700));
//		} else if (StringUtils.isEmpty(merchantDef.getBannerImage()) && StringUtils.isEmpty(merchantDef.getLogoImage())) {
//			merchantDef.setBannerImage(SysConstants.DEFAULT_PICTURE_DETAIL);
//		}		
	
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> products = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			erpProduct.setShowMemPrice(merchandise.getPrice());
			
			// 商品图片---多张			
			if (StringUtils.isEmpty(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl().split(",")[0], 300, 300));
			}
			products.add(erpProduct);
		}
		Map<String, Object> data = new HashMap<String, Object>();

		// 请求微信 js api的完整页面地址
		String url = httpRequest.getScheme()+"://"; // 请求协议 http 或 https 
		url+=httpRequest.getServerName(); // 请求服务器 
		url+=httpRequest.getRequestURI(); // 工程名
		if(httpRequest.getQueryString()!=null) { //判断请求参数是否为空
			url+="?"+httpRequest.getQueryString(); // 参数
		}
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		
		List<MrtMerchantCarousel> carousels = mrtMerchantCarouselService.getMrtMerchantCarouselList(mid);
		String carouselBaseUrl = getCaruselBaseURL(httpRequest);
		if (carousels != null && carousels.size() > 0) {
			if (carousels.size() == 1) {
				 data.put("bannerPath1", carouselBaseUrl + carousels.get(0).getFilePaths());
				 data.put("bannerUrl1", carousels.get(0).getFileUrl());
			} else if (carousels.size() == 2) {
				 data.put("bannerPath1", carouselBaseUrl + carousels.get(0).getFilePaths());
				 data.put("bannerPath2", carouselBaseUrl + carousels.get(1).getFilePaths());
				 data.put("bannerUrl1", carousels.get(0).getFileUrl());
				 data.put("bannerUrl2", carousels.get(1).getFileUrl());
			} else if (carousels.size() > 2) {
				 data.put("bannerPath1", carouselBaseUrl + carousels.get(0).getFilePaths());
				 data.put("bannerPath2", carouselBaseUrl + carousels.get(1).getFilePaths());
				 data.put("bannerPath3", carouselBaseUrl + carousels.get(2).getFilePaths());
				 data.put("bannerUrl1", carousels.get(0).getFileUrl());
				 data.put("bannerUrl2", carousels.get(1).getFileUrl());
				 data.put("bannerUrl3", carousels.get(2).getFileUrl());
			}
		}
		
		data.put("dns", messageSource.getMessage(SysConstants.SERVICE_DNS, null,
				Locale.ENGLISH));
//		data.put("merchant", merchantDef);
		data.put("products", products);
		data.put("mid", mid);
		return new ModelAndView("dgd_order/index", data);
	}
	
	private String getCaruselBaseURL(HttpServletRequest httpRequest) {
		String baseUrl = messageSource.getMessage(SysConstants.CAROUSEL_PATH, null,
								Locale.ENGLISH);
		return baseUrl;
	}
	
	private String getBaseURL(HttpServletRequest httpRequest) {
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		return baseUrl;
	}
	
	@RequestMapping(value = "/toIndex")
	public ModelAndView mystore(
			@RequestParam(value = "mid") String mid,
			HttpServletRequest httpRequest) {
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");	
		}
		Map<String, Object> data = new HashMap<String, Object>();

		data.put("mid", mid);
		data.put("cardId", cardId);
		return new ModelAndView("index/mystore", data);
	}
	
	@RequestMapping(value = "/get_product")
	@ResponseBody
	public List<ErpProduct> getProduct(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			@RequestParam(value = "nextPage", defaultValue = "1") Integer nextPage,
			HttpServletRequest httpRequest) {
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		producthotInput.setName(keyWord);
		producthotInput.setPageNo(nextPage.toString());
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		Page<ErpProduct> page = new Page<ErpProduct>();
		page.setPageNo(nextPage);

		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 300, 300));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		return producthot;
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public ModelAndView search(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			HttpServletRequest httpRequest)
					throws UnsupportedEncodingException {
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");	
		}		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		if (!"".equals(keyWord)) {
			keyWord = URLDecoder.decode(keyWord, "UTF-8");// 防止中文乱码
		}
		producthotInput.setName(keyWord);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		Map<String, Object> getpriceMhot = new HashMap<String, Object>();
		Map<String, Object> getmberpriceMhot = new HashMap<String, Object>();
		if (!"".equals(keyWord)) {
			keyWord = URLDecoder.decode(keyWord, "UTF-8");// 防止中文乱码
		}
		logger.info("开始搜索产品,catagoryId:" + categoryId + "keyWord:" + keyWord);
		
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 300, 300));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}

		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("categoryId", categoryId);
		data.put("mid", mid);
		data.put("keyWord", keyWord);
		return new ModelAndView("productcategory/prolist", data);
	}

	@RequestMapping(value = "/toSearch", method = RequestMethod.GET)
	public ModelAndView toSearch(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			HttpServletRequest httpRequest)
			throws UnsupportedEncodingException {
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");	
		}		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();

		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 300, 300));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		data.put("getpricehot", getpricehot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("categoryId", categoryId);
		data.put("mid", mid);
		return new ModelAndView("index/searchPage", data);
	}

	@RequestMapping(value = "/searchAll", method = RequestMethod.GET)
	public ModelAndView searchAll(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			Model model, HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");	
		}		
		
		if (StringUtils.isNotEmpty(keyWord)) {
			keyWord = URLDecoder.decode(keyWord, "UTF-8");// 防止中文乱码
		}		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		producthotInput.setName(keyWord);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		Map<String, Object> getpriceMhot = new HashMap<String, Object>();
		Map<String, Object> getmberpriceMhot = new HashMap<String, Object>();

		logger.info("开始搜索产品," + "keyWord" + keyWord);

		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 300, 300));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}

		data.put("getpricehot", getpricehot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("categoryId", categoryId);
		data.put("mid", mid);
		model.addAttribute("keyWord", keyWord);
		return new ModelAndView("index/searchPage", data);
	}

	/**
	 * 商品名称过长，做部分截取
	 * 
	 * @param erpProduct
	 */
	private void formatProdName(ErpProduct erpProduct) {
		String name = erpProduct.getName();
		if (name != null && name.length() > 23) {
			erpProduct.setName(name.substring(0, 20) + "...");
		}
	}
	
	
	@RequestMapping(value = "/ys", method = RequestMethod.GET)
	public ModelAndView ys(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		//获取商户信息
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput,"/merchantdef/info",MerchantDefQueryOutput.class);
		MerchantDef merchant = merchantDefQueryOutput.getResult();
		if (merchant == null) {
			data.put("err_message", "该商户不存在");
			return new ModelAndView("error", data);
		}
		data.put("merchant", merchant);
		data.put("openId", openId);
		data.put("mid", mid);
				
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();
		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 300, 300));
			}
			producthot.add(erpProduct);
		}
		data.put("producthot", producthot);
		data.put("getmberpricehot", getmberpricehot);
		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/index/ys");
		tmpUrl.append("?openId=").append(openId);
		tmpUrl.append("&mid=").append(mid);
		String url = tmpUrl.toString();
		
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		
		return new ModelAndView("ys/ys", data);
	}
}
